package com.ryskoo.basicdata.area.province.repository;

import com.ryskoo.basicdata.area.city.repository.ICityRepository;
import com.ryskoo.basicdata.area.province.domain.ProvincePO;
import com.ryskoo.basicdata.area.region.repository.IRegionRepository;
import com.ryskoo.common.constant.CacheConstant;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author qyc
 */
@Primary
@Repository
public class ProvinceRedisImpl extends BasicRedisImpl<ProvincePO> implements IProvinceRepository{
    @Autowired
    private RedisUtil redisClient;

    @Autowired
    private IProvinceRepository provinceRepository;
    
    @Autowired
    private ICityRepository cityRepository;
    
    @Autowired
    private IRegionRepository regionRepository;

    /**
     * 省缓存KEY
     */
    private static final String cacheKey = CacheConstant.BDS_AREA_PROVINCE_KEY;
    /**
     * 省集合缓存KEY
     */
    private static final String cacheListKey = CacheConstant.BDS_AREA_PROVINCE_LIST_KEY;

    @PostConstruct
    public void init() {
        this.setRedisClient(redisClient);
        this.setDao(provinceRepository);
    }

    public ProvinceRedisImpl() {
        super(cacheKey);
    }

    
	@Override
	public List<ProvincePO> getAll() {
		//1.从缓存获取所有的地区-省
		Object object = redisClient.getSession(cacheListKey);
		if (object != null) {
            List<ProvincePO> cacheList = (List<ProvincePO>)object;
            return cacheList;
        }
		//2.缓存中如果没有取到，则从数据库中获取
		List<ProvincePO> dbList = super.getAll();
		
		//3.将结果放入缓存
        redisClient.setExpireSession(cacheListKey, dbList, null);

		return dbList;
	}

	@Override
	public void initArea() {
		//1.初始化地区-省
		this.getAll();
		//2.初始化地区-市
		cityRepository.getAll();
		//3.初始化地区-区县
		regionRepository.getAll();
	}

    @Override
    public ProvincePO getByEntityNo(String entityNo) {
        return provinceRepository.getByEntityNo(entityNo);
    }
}
